/*-------------------------------------------------------------------------
 *
 * discard.c
 *	  DISCARD 命令的实现
 *
 * Copyright (c) 1996-2022, PostgreSQL Global Development Group
 *
 *
 * IDENTIFICATION
 *	  src/backend/commands/discard.c
 *
 *-------------------------------------------------------------------------
 */
#include "postgres.h"

#include "access/xact.h"
#include "catalog/namespace.h"
#include "commands/async.h"
#include "commands/discard.h"
#include "commands/prepare.h"
#include "commands/sequence.h"
#include "utils/guc.h"
#include "utils/portal.h"

static void fc_DiscardAll(bool fc_isTopLevel);

/*
 * 丢弃 { ALL | SEQUENCES | TEMP | PLANS }
 */
void DiscardCommand(DiscardStmt *fc_stmt, bool fc_isTopLevel)
{
	switch (fc_stmt->target)
	{
		case DISCARD_ALL:
			fc_DiscardAll(fc_isTopLevel);
			break;

		case DISCARD_PLANS:
			ResetPlanCache();
			break;

		case DISCARD_SEQUENCES:
			ResetSequenceCaches();
			break;

		case DISCARD_TEMP:
			ResetTempTableNamespace();
			break;

		default:
			elog(ERROR, "unrecognized DISCARD target: %d", fc_stmt->target);
	}
}

static void fc_DiscardAll(bool fc_isTopLevel)
{
	/*
	 * 在事务块中不允许使用丢弃 ALL。这在某种程度上
	 * 是不一致的（我们在与之等效的命令序列中没有类似的检查），但目的是抓住错误：
	 * 在事务块中使用丢弃 ALL 会使得事务
	 * 仍然未提交。
	 */
	PreventInTransactionBlock(fc_isTopLevel, "DISCARD ALL");

	/* 关闭门户可能会运行用户定义的代码，所以首先执行这个。 */
	PortalHashTableDeleteAll();
	SetPGVariable("session_authorization", NIL, false);
	ResetAllOptions();
	DropAllPreparedStatements();
	Async_UnlistenAll();
	LockReleaseAll(USER_LOCKMETHOD, true);
	ResetPlanCache();
	ResetTempTableNamespace();
	ResetSequenceCaches();
}
